package com.mypage.view.activity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreContainer;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.mobile.AppConfig;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.weight.ClearEditText;
import com.cloudcc.mobile.widget.listview.CloudCCListView;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.mypage.adapter.NDefauleChageListAdapter;
import com.mypage.adapter.NewContactLianxiadapter;
import com.mypage.bean.CustomListBean;
import com.mypage.model.NewcontactLixnxi;
import com.mypage.utils.RecordSQLiteOpenHelper;
import com.mypage.utils.UtilsShowDialog;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NewContactLianXi extends BaseActivity implements CloudCCListView.OnRefreshOrLoadMoreListener{
    public List<CustomListBean.CustomData.Custom> mList;
    public List<NewcontactLixnxi.Custom> mQList;
    public NewContactLianxiadapter mAdapter;
    private String  recordId,layoutId,relatedlistId;
    public NDefauleChageListAdapter mDefaultAdapter;
    public static NewContactLianXi instance = null;
    @Bind(R.id.searchData)
    TextView searchData;
    @Bind(R.id.searchDataButtonLine)
    View searchDataButtonLine;
    @Bind(R.id.noContent)
    TextView noContent;
    @Bind(R.id.noContentButtonLine)
    View noContentButtonLine;
    @Bind(R.id.textUser)
    TextView textUser;
    private UtilsShowDialog showDialog;
    @Bind(R.id.btnImgBack)
    ImageView btnImgBack;
    @Bind(R.id.etSearchContent)
    ClearEditText etSearchContent;
    @Bind(R.id.imgClean)
    ImageView imgClean;
    @Bind(R.id.listCustom)
    CloudCCListView listCustom;
    @Bind(R.id.noshitu)
    TextView noshitu;

    @Bind(R.id.tv_clear)
    TextView tvClear;
//    @Bind(R.id.linearLayout)
//    LinearLayout linearLayout;
    private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
    private SQLiteDatabase db;
    private BaseAdapter adapter;
    private int page = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_contact_lianxi);
        ButterKnife.bind(this);
        instance = this;
        showDialog = new UtilsShowDialog(this);
        listCustom.setOnRefreshOrLoadMoreListener(this);
        initdata();
        mHttpQueryData();
        //        getDataHttp();//默认访问用户列表
        textChange();
        initView();
        initListener();
    }
    @Override
    public int getLayoutId() {
        return R.layout.activity_new_contact_lianxi;
    }
    private void initdata() {
        Intent intent = getIntent();
        recordId = intent.getStringExtra("recordId");
        layoutId = intent.getStringExtra("layoutId");
        relatedlistId = intent.getStringExtra("relatedlistId");
    }
    //监听输入框的变化
    public void textChange() {
        // 搜索框的文本变化实时监听
        etSearchContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                String mContent = etSearchContent.getText().toString();
                noContent.setVisibility(View.GONE);
                noContentButtonLine.setVisibility(View.GONE);
//                mHttpQueryData();
                if ("".equals(mContent)) {
                    searchData.setVisibility(View.GONE);
                    searchDataButtonLine.setVisibility(View.GONE);
//                    imgClean.setVisibility(View.GONE);
                } else {
//                    imgClean.setVisibility(View.VISIBLE);
                    searchData.setVisibility(View.VISIBLE);
                    searchDataButtonLine.setVisibility(View.VISIBLE);
                    searchData.setText("搜索”" + mContent + "“");

                }


            }

            @Override
            public void afterTextChanged(Editable s) {

//                String tempName = etSearchContent.getText().toString();
//                // 根据tempName去模糊查询数据库中有没有数据
//                queryData(tempName);

            }
        });
    }

    public void initView() {
            textUser.setText(getResources().getString(R.string.lianxirenxuanze));
    }
    public void initListener() {
        etSearchContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // TODO: 2017/5/11
//                    showDialog.onShowLoadingDialog("正在加载...");
//                    mQList.clear();
                    page = 1;
                    mHttpQueryData();
                    searchData.setVisibility(View.GONE);
                    searchDataButtonLine.setVisibility(View.GONE);
                }
                return false;
            }
        });
        listCustom.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });
        //搜索
        tvClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
                mHttpQueryData();
                listCustom.setVisibility(View.VISIBLE);
//                linearLayout.setVisibility(View.INVISIBLE);
                Toast.makeText(NewContactLianXi.this, etSearchContent.getText().toString(), Toast.LENGTH_SHORT)
                        .show();
                //                //删除数据库的历史记录
                //                deleteData();
                //                queryData("");
            }
        });
        // 第一次进入查询所有的历史记录
//        queryData("");
    }

    @OnClick(R.id.searchData)
    public void searchData() {
        showDialog.onShowLoadingDialog(getString(R.string.nowjiazai));
        mHttpQueryData();
        searchData.setVisibility(View.GONE);
        searchDataButtonLine.setVisibility(View.GONE);
        if (mQList.size() == 0) {
            searchData.setVisibility(View.GONE);
            searchDataButtonLine.setVisibility(View.GONE);
            noContent.setVisibility(View.VISIBLE);
            noContentButtonLine.setVisibility(View.VISIBLE);
            noContent.setText(getString(R.string.pipeijieguo) + etSearchContent.getText().toString() + getString(R.string.jieguopipie));
        }
        //    Toast.makeText(this,"sssssssssss",3).show();
    }

    @OnClick({R.id.btnImgBack, R.id.imgClean})
    public void setOnClick(ImageView v) {
        switch (v.getId()) {
            case R.id.imgClean:
                etSearchContent.setText("");
                break;
            case R.id.btnImgBack:
                finish();
                break;

        }
    }


    /**
     * 点击按钮隐藏键盘
     */
    public void setKeyBoard() {
        InputMethodManager inputMethodManager = (InputMethodManager) this.getApplicationContext().
                getSystemService(NewContactLianXi.this.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(etSearchContent.getWindowToken(), 0); //隐藏
    }


    /**
     * 模糊查询数据
     */
//    private void queryData(String tempName) {
//        Cursor cursor = helper.getReadableDatabase().rawQuery(
//                "select id as _id,name from records where name like '%"
//                        + tempName + "%' order by id desc ", null);
//        // 创建adapter适配器对象
//        adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[]{"name"}, new int[]{android.R.id.text1},
//                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
//        // 设置适配器
//        listView.setAdapter(adapter);
//        adapter.notifyDataSetChanged();
//
//    }

    /**
     * 检查数据库中是否已经有该条记录
     */
    private boolean hasData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name =?",
                new String[]{tempName});
        // 判断是否有下一个
        return cursor.moveToNext();
    }

    /**
     * 清空数据
     */
    private void deleteData() {
        db = helper.getWritableDatabase();
        db.execSQL("delete from records");
        db.close();
    }

    /**
     * 插入数据
     */
    private void insertData(String tempName) {
        db = helper.getWritableDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }


    public void saveData() {
        // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
        boolean hasData = hasData(etSearchContent.getText()
                .toString().trim());
        if (!hasData) {
            insertData(etSearchContent.getText().toString()
                    .trim());
//            queryData("");
        }
    }
private  List<NewcontactLixnxi.Custom> newQlist;
    public void mHttpQueryData() {
        showDialog.onShowLoadingDialog(getString(R.string.xlistview_header_hint_loading));
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "getLookupConcat");
        params.addBodyParameter("keyword", etSearchContent.getText().toString());
        params.addBodyParameter("opportunityId", recordId);
        params.addBodyParameter("pageSize","50");
        params.addBodyParameter("pageNUM", String.valueOf(page));
        Log.d("request查询用户列表url", UrlManager.getInterfaceUrl() + "?binding=" + RunTimeManager.getInstance().getServerBinding()
                + "&serviceName=getLookupConcat" + "&keyword=" + etSearchContent.getText().toString()
                + "&opportunityId="+recordId+"&pageSize="+"50"+"&pageNUM="+String.valueOf(page));
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                Log.d("request查询客户Fail", arg1);
                if (isFromRefresh()) {
                    listCustom.refreshComplete();
                    listCustom.handlerLoadMoreFinish(true, false);
                } else {
                    listCustom.handlerLoadMoreError(1002, arg1);
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                showDialog.onDismissLoadingDialog();
                listCustom.refreshComplete();
//                listCustom.handlerLoadMoreFinish(true, false);
                Log.d("request查询客户Success", arg0.result.toString());
                NewcontactLixnxi mCustom = new Gson().fromJson(arg0.result.toString(), NewcontactLixnxi.class);
//                mQList = new ArrayList<NewcontactLixnxi.Custom>();
                mQList = mCustom.data;
                if(null==mQList){
                    noContent.setVisibility(View.GONE);
                    listCustom.setVisibility(View.GONE);
                    noshitu.setVisibility(View.VISIBLE);
                    return;
                }else{
                    listCustom.setVisibility(View.VISIBLE);
                    noshitu.setVisibility(View.GONE);
                }
                if( 0==mQList.size()&&page==1){
                    noContent.setVisibility(View.GONE);
                    listCustom.setVisibility(View.GONE);
                    return;
                }else{
                    listCustom.setVisibility(View.VISIBLE);
                    noshitu.setVisibility(View.GONE);
                }

                if(0<mQList.size()&&mQList.size()<13){
                    if (isFromRefresh()) {
                        listCustom.refreshComplete();
                        listCustom.handlerLoadMoreFinish(false, false);
                    } else {
                        listCustom.refreshComplete();
                        listCustom.handlerLoadMoreFinish(false, false);// 不是来自刷新 是来自
//                    listCustom.handlerLoadMoreError(1002, "加载失败");
                    }
                }else{
                    onRequestFinish(ListUtils.isEmpty(mQList));
                }
                if (mQList.size()>= 0) {

                    showDialog.onDismissLoadingDialog();
                    listCustom.setVisibility(View.VISIBLE);
                }

                if (mAdapter == null) {
                    mAdapter = new NewContactLianxiadapter(mQList, NewContactLianXi.this, etSearchContent.getText().toString());
                    listCustom.setAdapter(mAdapter);
                    showDialog.onDismissLoadingDialog();
                } else {
                    if (!isFromRefresh()) {
                        Log.d("zoudaolenali", "開始匹配+BeauListEvent");
                        mAdapter.addData(mQList);
                    }else{
                        mAdapter = new NewContactLianxiadapter(mQList, NewContactLianXi.this, etSearchContent.getText().toString());
                        listCustom.setAdapter(mAdapter);
//                        mAdapter.changeData(mQList);
                        showDialog.onDismissLoadingDialog();

                    }
                }
            }
        });


    }

    @Override
    public void onRefresh(PtrFrameLayout frame) {
        page = 1;
        mHttpQueryData();
//        listCustom.refreshComplete();
//        listCustom.handlerLoadMoreFinish(true, false);

    }

    @Override
    public void onLoadMore(LoadMoreContainer frame) {
        page++;
        mHttpQueryData();

    }
    private void onRequestFinish(boolean dataIsEmpty) {
        if (isFromRefresh()) {// 第一次加载 并且数据出现空的话 就显示 空
            listCustom.refreshComplete();
            listCustom.handlerLoadMoreFinish(dataIsEmpty, !dataIsEmpty);// 第一次加载
            listCustom.isfirst();
        } else {
            listCustom.refreshComplete();
            listCustom.handlerLoadMoreFinish(false, !dataIsEmpty);// 不是来自刷新 是来自
            // 上啦加载更多
            // 这样的话
        }
    }
        protected boolean isFromRefresh() {
            return page <= AppConfig.DEFAULTPAGE;
        }
}
